package vip.george.p0043;

import java.math.BigInteger;


public class P43 {

    /**
     * <h2>字符串相乘</h2>
     * <p>解题思路：<p/>
     * <p>标准的竖式计算：<p/>
     * <img src="https://image-host-dev.oss-cn-hangzhou.aliyuncs.com/images/leetcode/43/calculate-1.png">
     *
     * <p>非标准的竖式计算：<p/>
     *
     * <img src="https://image-host-dev.oss-cn-hangzhou.aliyuncs.com/images/leetcode/43/calculate-2.png">
     *
     *
     * 使用一个数组pos，用来保存中间积的和
     * @param num1
     * @param num2
     * @return
     */

    public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }
        int m = num1.length(), n = num2.length();

        //因为乘法结果长度最大为m+n
        int[] pos = new int[m + n];

        //从后往前遍历每个数字
        for (int i = m - 1; i >= 0; i--) {
            int x = num1.charAt(i) - '0';
            for (int j = n - 1; j >= 0; j--) {
                int y = num2.charAt(j) - '0';
                //本地相乘结果要累加到pos[i+j+1]
                pos[i + j + 1] += x * y;
            }
        }
        int carry = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = pos.length - 1; i >= 0; i--) {
            //如果第一位的数字为0，并且没有涉及到进位，则不需要添加进结果中
            if (i == 0 && carry == 0) {
                continue;
            }
            int currentValue = pos[i] + carry;
            int digit = (currentValue) % 10;
            carry = (currentValue) / 10;
            sb.append(digit);
        }
        return sb.reverse().toString();
    }

    public static void main(String[] args) {
        P43 p43 = new P43();
        System.out.println(p43.multiply("0", "0"));
        System.out.println(p43.multiply("1", "1"));
        System.out.println(p43.multiply("2", "3"));
        System.out.println(p43.multiply("9", "9"));
        System.out.println(p43.multiply("1234", "567"));
        System.out.println(p43.multiply("123456789", "987654321"));
        System.out.println(p43.multiply("123456789987654321123456789987654321", "123456789987654321123456789987654321"));
        BigInteger a = new BigInteger("123456789987654321123456789987654321");
        BigInteger b = new BigInteger("123456789987654321123456789987654321");
        System.out.println(a.multiply(b));
    }
}
